#!/bin/bash

# 设置配置主目录
if [ -z "$CONFIG_HOME" ]; then
  export CONFIG_HOME="${HOME}/.mac_sync"
fi

# 使用统一的全局包根目录结构
NODE_GLOBAL_ROOT="${HOME}/.node_global"
GROUP="modern"
NPM_GLOBAL_DIR="${NODE_GLOBAL_ROOT}/${GROUP}/npm"
PNPM_GLOBAL_DIR="${NODE_GLOBAL_ROOT}/${GROUP}/pnpm"

# 设置日志文件
LOG_FILE="${CONFIG_HOME}/logs/node_modern_setup_$(date +%Y%m%d_%H%M%S).log"
mkdir -p "$(dirname "$LOG_FILE")"

# 日志函数
log() {
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1" | tee -a "$LOG_FILE"
}

# 错误处理函数
handle_error() {
    local package=$1
    local attempt=$2
    local max_attempts=$3
    
    if [ $attempt -lt $max_attempts ]; then
        log "⚠️ 安装 $package 失败，尝试重新安装 (尝试 $attempt/$max_attempts)"
        return 1
    else
        log "❌ 安装 $package 失败，已达到最大重试次数"
        echo "$package" >> "${CONFIG_HOME}/logs/modern_failed_packages.txt"
        return 0
    fi
}

# 安装单个包的函数
install_package() {
    local package=$1
    local version=$2
    local full_package="$package"
    
    if [ ! -z "$version" ]; then
        full_package="$package@$version"
    fi
    
    local max_attempts=3
    local attempt=1
    
    while [ $attempt -le $max_attempts ]; do
        log "📦 正在安装 $full_package (尝试 $attempt/$max_attempts)"
        if pnpm add -g "$full_package" >> "$LOG_FILE" 2>&1; then
            log "✅ 成功安装 $full_package"
            return 0
        else
            handle_error "$full_package" $attempt $max_attempts || { attempt=$((attempt + 1)); continue; }
            return 1
        fi
    done
}

# 创建目录
mkdir -p "${NPM_GLOBAL_DIR}/bin"
mkdir -p "${PNPM_GLOBAL_DIR}/bin"
mkdir -p "${PNPM_GLOBAL_DIR}/store"

# 设置环境变量
export NPM_CONFIG_PREFIX="${NPM_GLOBAL_DIR}"
export PATH="${NPM_GLOBAL_DIR}/bin:$PATH"

# 清理之前的失败记录
rm -f "${CONFIG_HOME}/logs/modern_failed_packages.txt"

log "开始安装适用于 Node.js 20+ 的常用全局开发工具..."

# 先安装 pnpm (使用 npm 安装)
log "🔧 开始安装 pnpm..."
npm install -g pnpm@latest >> "$LOG_FILE" 2>&1
log "✨ pnpm 安装完成"
echo "----------------------------------------"

# 配置 pnpm
export PNPM_HOME="${PNPM_GLOBAL_DIR}"
export PATH="${PNPM_HOME}/bin:$PATH"
pnpm config set global-dir "${PNPM_HOME}"
pnpm config set global-bin-dir "${PNPM_HOME}/bin" 
pnpm config set store-dir "${PNPM_HOME}/store"
log "✨ pnpm 配置完成"
echo "----------------------------------------"

# 基础开发工具
log "🔧 开始安装基础开发工具..."
install_package "typescript" "latest"
install_package "ts-node" "latest"
install_package "nodemon" "latest"
install_package "pm2" "latest"
install_package "http-server" "latest"
install_package "serve" "latest"
install_package "json-server" "latest"
install_package "npm-check-updates" "latest"
log "✨ 基础开发工具安装完成"
echo "----------------------------------------"

# 前端框架 CLI
log "🔧 开始安装前端框架 CLI..."
install_package "@vue/cli" "latest"
install_package "@angular/cli" "latest"
install_package "create-react-app" "latest"
install_package "create-vite" "latest"
install_package "@nestjs/cli" "latest"
install_package "create-next-app" "latest"
install_package "@nuxt/create-app" "latest"
install_package "gatsby-cli" "latest"
install_package "@tarojs/cli" "latest"
install_package "@ionic/cli" "latest"
install_package "@quasar/cli" "latest"
log "✨ 前端框架 CLI 安装完成"
echo "----------------------------------------"

# 构建工具
log "🔧 开始安装构建工具..."
install_package "yarn" "latest"
install_package "webpack-cli" "latest"
install_package "rollup" "latest"
install_package "esbuild" "latest"
install_package "turbo" "latest"
install_package "vite" "latest"
install_package "unbuild" "latest"
install_package "swc-cli" "latest"
install_package "parcel" "latest"
log "✨ 构建工具安装完成"
echo "----------------------------------------"

# 工具链
log "🔧 开始安装工具链..."
install_package "eslint" "latest"
install_package "prettier" "latest"
install_package "@typescript-eslint/cli" "latest"
install_package "commitizen" "latest"
install_package "cz-conventional-changelog" "latest"
install_package "husky" "latest"
install_package "lint-staged" "latest"
install_package "stylelint" "latest"
install_package "postcss-cli" "latest"
install_package "sass" "latest"
install_package "less" "latest"
log "✨ 工具链安装完成"
echo "----------------------------------------"

# UI 开发工具
log "🔧 开始安装 UI 开发工具..."
install_package "@storybook/cli" "latest"
install_package "plop" "latest"
install_package "hygen" "latest"
log "✨ UI 开发工具安装完成"
echo "----------------------------------------"

# 调试和性能工具
log "🔧 开始安装调试和性能工具..."
install_package "autocannon" "latest"
install_package "clinic" "latest"
install_package "lighthouse" "latest"
install_package "source-map-explorer" "latest"
install_package "webpack-bundle-analyzer" "latest"
install_package "vite-bundle-analyzer" "latest"
log "✨ 调试和性能工具安装完成"
echo "----------------------------------------"

# 测试工具
log "🔧 开始安装测试工具..."
install_package "jest" "latest"
install_package "vitest" "latest"
install_package "cypress" "latest"
install_package "@playwright/test" "latest"
install_package "@testing-library/jest-dom" "latest"
log "✨ 测试工具安装完成"
echo "----------------------------------------"

# 文档工具
log "🔧 开始安装文档工具..."
install_package "docsify-cli" "latest"
install_package "vuepress" "latest"
install_package "typedoc" "latest"
install_package "jsdoc" "latest"
log "✨ 文档工具安装完成"
echo "----------------------------------------"

# 数据库工具
log "🔧 开始安装数据库工具..."
install_package "prisma" "latest"
install_package "typeorm" "latest"
install_package "sequelize-cli" "latest"
install_package "mongosh" "latest"
install_package "drizzle-kit" "latest"
log "✨ 数据库工具安装完成"
echo "----------------------------------------"

# API 开发工具
log "🔧 开始安装 API 开发工具..."
install_package "swagger-cli" "latest"
install_package "@graphql-codegen/cli" "latest"
install_package "graphql" "latest"
install_package "apollo" "latest"
log "✨ API 开发工具安装完成"
echo "----------------------------------------"

# 移动端开发
log "🔧 开始安装移动端开发工具..."
install_package "cordova" "latest"
install_package "@capacitor/cli" "latest"
install_package "react-native-cli" "latest"
log "✨ 移动端开发工具安装完成"
echo "----------------------------------------"

# 新兴技术工具
log "🔧 开始安装新兴技术工具..."
install_package "astro" "latest"
install_package "create-svelte" "latest"
install_package "remix-cli" "latest"
install_package "@microsoft/rush" "latest"
install_package "@nx/cli" "latest"
log "✨ 新兴技术工具安装完成"
echo "----------------------------------------"

# 实用工具
log "🔧 开始安装实用工具..."
install_package "npkill" "latest"
install_package "npm-why" "latest"
install_package "depcheck" "latest"
install_package "madge" "latest"
install_package "license-checker" "latest"
install_package "npm-check" "latest"
install_package "localtunnel" "latest"
install_package "live-server" "latest"
install_package "cross-env" "latest"
install_package "rimraf" "latest"
install_package "concurrently" "latest"
install_package "dotenv-cli" "latest"
install_package "nrm" "latest"
install_package "verdaccio" "latest"
install_package "fx" "latest"
install_package "zx" "latest"
install_package "ultra-runner" "latest"
install_package "changelogen" "latest"
install_package "release-it" "latest"
install_package "bunyan" "latest"
log "✨ 实用工具安装完成"
echo "----------------------------------------"

# 检查是否有安装失败的包
if [ -f "${CONFIG_HOME}/logs/modern_failed_packages.txt" ]; then
    log "⚠️ 以下包安装失败："
    cat "${CONFIG_HOME}/logs/modern_failed_packages.txt" | tee -a "$LOG_FILE"
    log "您可以稍后尝试手动安装这些包"
    log "安装日志已保存到：$LOG_FILE"
else
    log "🎉 所有包安装成功！"
fi

log "🚀 Node.js 20+ 环境设置完成！"
log "📁 所有全局包已安装到: ${NODE_GLOBAL_ROOT}/${GROUP}"
log "🔍 使用 'node-global' 命令可查看当前全局包目录信息" 